#!/usr/bin/env python
# coding=utf-8

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

__author__ = 'vavava'


import threading,time
from queue import Queue
from vavava.base import LogAdapter

class work(object):
    """
    base class for user-work-item,self.do() must be written over
    """
    def __init__(self,log=None):
        self.func=None
        self.log = LogAdapter(log)

    def do(self):
        self.log.error("Function building (work) ....")
        raise Exception("Function building ....")


class WorkQueue(object):
    def __init__(self,maxsize=100,log=None):
        self.thread=threading.Thread(target=self._do)
        self.works=Queue(maxsize)
        self.is_busy=threading.Event()    # work queue have work to do
        self.is_active=threading.Event()  # work queue is working
        self.is_active.set()
        self.log = LogAdapter(log)

    def _do(self,func=None):
        self.is_active.clear()
        while self.IsRunning:
            work = self.works.get(block=True,timeout=0.5)
            if not self.IsRunning:
                break
            if work:
                work.do() # working ...
            else:
                self.log.error("Invalid work item")
        self.is_active.set()

    def Start(self):
        if not self.IsRunning:
            self.is_active.clear()
            self.thread.start()
        else:
            self.log.warn("Queue is running")

    def Stop(self,timeout=10):
        if self.IsRunning:
            self.is_active.set()
            self.thread.join(timeout)
            self.log.debug("Stopped with %d work in queue."%self.works.qsize())

    def QueueWork(self,work):
        if not self.IsRunning:
            self.log.debug("Queue stopped when new work come.")
            return
        try:
            self.works.put(item=work,block=False)
        except:
            self.log.error("work queue is full")
            raise

    @property
    def IsBusy(self):
        return self.works.qsize() > 0

    @property
    def IsRunning(self):
        return not self.is_active.is_set()


class MyWork(work):
    def __init__(self,seq=0,log=None):
        work.__init__(self, log)
        self.seq=seq

    def do(self):
        import time
        print("Hello DB !!!!!!! %d"%self.seq)
        time.sleep(1)
        print("CU DB !!!!!!! %d"%self.seq)

def main():
    workingLine=WorkQueue()
    workingLine.Start()
    try:
        seq=0
        while seq < 100:
            import time
            seq += 1
            print("Add a work : %d"%seq)
            workingLine.QueueWork(MyWork(seq))
            time.sleep(1)
    except(KeyboardInterrupt):
        print('main thread(%f):stop'%time.clock())
        workingLine.Stop()
        print('main thread(%f):stopped'%time.clock())

if __name__ == '__main__':
    main()



